package com.microlecture.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.microlecture.common.Constants;
import com.microlecture.common.DataPacket;
import com.microlecture.entity.Cookbook;
import com.microlecture.mapper.CookbookMapper;
import com.microlecture.service.CookbookService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class CookbookServiceImpl implements CookbookService {

    @Autowired
    private CookbookMapper cookbookMapper;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return cookbookMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insertSelective(Cookbook record) {
        return cookbookMapper.insertSelective(record);
    }

    @Override
    public Cookbook selectByPrimaryKey(Integer id) {
        return cookbookMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Cookbook record) {
        return cookbookMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public Map<String, Object> selectPageByCondition(int page, int rows, Integer userid, String searchContent, String orderBy) {
        Page<Cookbook> paging = PageHelper.startPage(page, rows);
        if(!StringUtils.isEmpty(orderBy)) {
            paging.setOrderBy(orderBy);
        }
        List<Cookbook> list = cookbookMapper.selectPageByCondition(userid, searchContent);
        Map<String, Object> result = DataPacket.dataGridResult(paging.getTotal(), list);
        result.put("currentPage", paging.getPageNum());
        result.put("totalPage", (int) Math.ceil(Double.valueOf(paging.getTotal()) / Constants.pageSize));
        result.put("page", paging);
        result.put("searchContent", searchContent);
        return result;
    }
}